package com.frontop.terminal.interceptor;

import com.alibaba.fastjson.JSON;
import com.frontop.terminal.enums.HeaderEnum;
import com.frontop.terminal.enums.ResultCodeEnum;
import com.frontop.terminal.model.vo.RestResult;
import com.frontop.terminal.util.SystemMonitoringUtil;
import com.frontop.terminal.util.TerminalRsaUtil;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author ccc
 */
@SuppressWarnings("AlibabaUndefineMagicConstant")
@Slf4j
public class AuthInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(@NonNull HttpServletRequest request,
                             @NonNull HttpServletResponse response,
                             @NonNull Object handler) throws Exception {
        //如果是本机请求不拦截
        String localIp = SystemMonitoringUtil.getTerminal().getIp();
        if (request.getLocalAddr().equals(localIp) || "127.0.0.1".equals(request.getLocalAddr())) {
//            log.info("本机请求不拦截, uri:{} ", request.getRequestURI());
            return true;
        }
        //获取认证信息
        String token = request.getHeader(HeaderEnum.TERMINAL_TOKEN.getKey());
        if (Strings.isEmpty(token)) {
            log.info("请求未携带Token，返回异常错误, uri:{} ", request.getRequestURI());
            httpServletResponseWriter(response, ResultCodeEnum.UNAUTHORIZED);
            return true;
        }
        if (!TerminalRsaUtil.terminalTokenResolver(token)) {
            log.info("无效的登录令牌，返回异常错误, uri:{} ", request.getRequestURI());
            httpServletResponseWriter(response, ResultCodeEnum.UNAUTHORIZED);
            return false;
        }
        return true;
    }

    private void httpServletResponseWriter(HttpServletResponse response, ResultCodeEnum resultCode) throws IOException {

        response.setStatus(ResultCodeEnum.FORBIDDEN.getCode());
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(JSON.toJSONString(RestResult.failed(resultCode)));
    }
}
